package com.af.financeomine.web.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.vraptor.Interceptor;
import org.vraptor.LogicException;
import org.vraptor.LogicFlow;
import org.vraptor.view.ViewException;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;

public class LoginInterceptor implements Interceptor{

	String [] allowed = {"aleqi200","fabyanjos"};
	
	private UserService userService;
	
	public LoginInterceptor(UserService userService) {
		this.userService = userService;
	}
	
	public void intercept(LogicFlow flow) throws LogicException, ViewException {
		
		HttpServletResponse resp = flow.getLogicRequest().getResponse();
		HttpServletRequest req = flow.getLogicRequest().getRequest();
		
		User user = userService.getCurrentUser();
		if(user!=null){
			boolean ok = false;
			if(flow.getLogicRequest().getSessionContext().getAttribute("user")==null){
				flow.getLogicRequest().getSessionContext().setAttribute("user", user);
			}
			for(String s : allowed){
				if(s.equals(user.getNickname())){
					flow.execute();
					ok = true;
				}
			}
			try{
				if(!ok)
					resp.sendRedirect("unautorized.html");
			} catch (IOException e) {
				throw new LogicException("Um erro inesperado ocorreu");
			}
		}else{
			try {
				resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
			} catch (IOException e) {
				throw new LogicException("Um erro inesperado ocorreu");
			}
		}
	}

}
